package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowBorrowList
 */
@WebServlet("/ShowBorrowList")
public class ShowBorrowList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String searchtype = request.getParameter("types4");
		String searchinfo = request.getParameter("searchinfo4");
		if (searchtype == null)
			searchtype = "bid";
		if (searchinfo == null)
			searchinfo = "";
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		try {
			Connection con = dbOperator.BasicOperation.getConnection();
			ResultSet rs;
			rs = dbOperator.AdvancedOperation.getBorrowList(con, searchinfo, searchtype);
			while (rs.next()) {
				out.print("<tr>");
				String bookID = rs.getString(3);
				String status = rs.getString(5);
				if(status.equals("borrowed"))out.println("<td id=\"rid" + bookID + "\">" + rs.getString(1) + "</td>");
				else out.println("<td>" + rs.getString(1) + "</td>");
				out.println("<td>" + rs.getString(2) + "</td>");
				out.println("<td>" + bookID + "</td>");
				String datestr = rs.getString(4);
				out.println("<td>" + datestr + "</td>");
				out.println("<td>" + status + "</td>");
				if (status.equals("borrowed")) {
					double fine = dbOperator.AdvancedOperation.getExpiredFine(con, datestr);
					if (fine > 0) {
						out.print("<td><input type=\"button\" class=\"btn btn-danger\" value=\"payfine\" name=\""
								+ bookID + fine
								+ "\" onclick=\"returnExpiredBook(this)\" data-toggle='modal' data-target='#returnExpiredBook'></td>");
					} else {
						out.print("<td><input type=\"button\" class=\"btn btn-primary\" value=\"return\" name=\"rtn"
								+ bookID
								+ "\" onclick=\"returnBook(this)\" data-toggle='modal' data-target='#returnBook'></td>");
					}
				}
				out.print("</tr>");
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
